package com.shouhuobao.take.wallet;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.shouhuobao.station.R;
import com.shouhuobao.station.wxapi.Constants;
import com.shouhuobao.take.identity.AuthenticationActivity;
import com.shouhuobao.take.model.WXUserInfoBean;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by joker on 2017/8/8.
 * 绑定微信账号
 */
public class BindWXAccoutActivity extends BaseActivity2 implements View.OnClickListener {

    /********************************************身份证认证****************************************/
    private TextView mUserInfoTV;//实名认证的名字和身份证号
    private LinearLayout mReviewLL;//审核中提示
    private TextView mInformationOrAlterTV;//认证或修改
    /*******************************************微信绑定 ******************************************/
    private TextView mWXNameTV;//微信名字
    private TextView mBindWXTV;//绑定微信或解绑微信

    private int isFrom = 0;//判断从哪个页面进来的，默认是 0 我的钱包页面  1 提现页面
    private int isBindWX = 0;//1 已经绑定  0未绑定
    private int isAuthentication = 0;// 1 已经认证 0 未认证  2 正在审核中

    private String headerImageUrl = "";
    private String openId = "";
    private String nickName = "";

    private String idName = "";
    private String idCard = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog(null);
        AppHttp.getInstance().queryIsBindWX();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_wallet_bindwxaccout);
        super.findViewById();
        getAppTitle().setCommonTitle("实名与账户");
        mWXNameTV = (TextView) findViewById(R.id.wx_name_TV);
        mBindWXTV = (TextView) findViewById(R.id.bindwx_TV);
        mBindWXTV.setOnClickListener(this);
        //*******************************************身份证认证***********************//
        mUserInfoTV = (TextView) findViewById(R.id.user_information_TV);
        mReviewLL = (LinearLayout) findViewById(R.id.review_LL);
        mInformationOrAlterTV = (TextView) findViewById(R.id.information_TV);
        mInformationOrAlterTV.setOnClickListener(this);

        isFrom = getIntent().getIntExtra("isFrom", 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //绑定或解绑微信账号
            case R.id.bindwx_TV:
                if (isBindWX == 1) {//已经绑定，解除绑定
                    showLoadingDialog(null);
                    AppHttp.getInstance().deleteWXAccout();
                } else {//进行绑定
                    IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
                    msgApi.registerApp(Constants.APP_ID);
                    final SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "com.shouhuobao.station";
                    msgApi.sendReq(req);
                }
                break;
            //身份证认证或修改
            case R.id.information_TV:
                Intent intent = new Intent(getContext(), AuthenticationActivity.class);
                if (isAuthentication == 1) {//已经认证，进行修改操作
                    intent.putExtra("isFrom", 0);
                    intent.putExtra("idName", idName);
                    intent.putExtra("idCard", idCard);
                } else {//进行认证操作
                    intent.putExtra("isFrom", 1);
                }
                startActivityForResult(intent, 101);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //微信登录获取accessToken值用于后期操作
            case MsgID.get_wx_login_token:
                final ReqResult<?> result = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result)) {
                            showLoadingDialog(null);
                            String jsonStr = result.getResult().toString();
                            try {
                                JSONObject jsonObject = new JSONObject(jsonStr);
                                String opneId = jsonObject.getString("openid").toString();
                                String access_token = jsonObject.getString("access_token").toString();
                                if (isNotEmpty(opneId) && isNotEmpty(access_token)) {
                                    AppHttp.getInstance().getUserMesg(access_token, opneId);
                                } else {
                                    cancelLoadingDialog();
                                    showToast("微信授权异常");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            cancelLoadingDialog();
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            //微信登录获取微信用户信息
            case MsgID.get_wx_login_userinfo:
                String message = (String) msg.obj;
                try {
                    JSONObject object = new JSONObject(message);
                    openId = object.getString("openid").toString();
                    nickName = object.getString("nickname").toString();
                    headerImageUrl = object.getString("headimgurl").toString();
                    AppHttp.getInstance().bindWXAccout(openId, nickName, headerImageUrl);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return true;
            //绑定微信进行回调
            case MsgID.bind_wx_accout:
                cancelLoadingDialog();
                final ReqResult<?> result1 = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result1)) {
                            isBindWX = 1;
                            showToast("绑定成功");
                            mWXNameTV.setText(nickName);
                            mBindWXTV.setText("解绑");
                            if (isFrom != 0) {
                                Intent intent = new Intent();
                                intent.putExtra("nickname", nickName);
                                intent.putExtra("openId", openId);
                                setResult(Activity.RESULT_OK, intent);
                                finish();
                            }
                        } else {
                            isBindWX = 0;
                            showToast(result1.getMessage());
                            mWXNameTV.setText("绑定微信账号");
                            mBindWXTV.setText("立即绑定");
                        }
                    }
                });
                return true;
            //解除微信绑定
            case MsgID.delete_wx_accout:
                cancelLoadingDialog();
                final ReqResult<?> result2 = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result2)) {
                            isBindWX = 0;
                            headerImageUrl = "";
                            mWXNameTV.setText("绑定微信账号");
                            mBindWXTV.setText("立即绑定");
                        } else {
                            showToast(result2.getMessage());
                        }
                    }
                });
                return true;
            //查询是否绑定微信和实名认证
            case MsgID.query_isbind_wx:
                cancelLoadingDialog();
                final ReqResult<WXUserInfoBean> result3 = JSON.parser(msg.obj, WXUserInfoBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result3) || result3.getStatus() == 0) {
                            WXUserInfoBean bean = result3.getResult();
                            if (result3.isSuccess()) {
                                if (isNotEmpty(bean.getOpenId())) {
                                    isBindWX = 1;
                                    mWXNameTV.setText(bean.getWxAccountName());
                                    mBindWXTV.setText("解绑");
                                } else {
                                    isBindWX = 0;
                                    mWXNameTV.setText("绑定微信");
                                    mBindWXTV.setText("立即绑定");
                                }
                                if (bean.getIdStatus() == 11) {//审核成功
                                    isAuthentication = 1;
                                    idName = bean.getIdName();
                                    idCard = bean.getIdCard();
                                    mReviewLL.setVisibility(View.GONE);
                                    mInformationOrAlterTV.setVisibility(View.VISIBLE);
                                    mInformationOrAlterTV.setText("修改");
                                    mUserInfoTV.setText(bean.getIdName() + "  " + bean.getIdCard());
                                } else if (bean.getIdStatus() == 1) {//正在审核中
                                    isAuthentication = 2;
                                    idName = bean.getIdName();
                                    idCard = bean.getIdCard();
                                    mReviewLL.setVisibility(View.VISIBLE);
                                    mInformationOrAlterTV.setVisibility(View.GONE);
                                    mUserInfoTV.setText(bean.getIdName() + "  " + bean.getIdCard());
                                } else {
                                    isAuthentication = 0;
                                    mUserInfoTV.setText("实名认证");
                                    mInformationOrAlterTV.setText("立即认证");
                                    mReviewLL.setVisibility(View.GONE);
                                    mInformationOrAlterTV.setVisibility(View.VISIBLE);
                                }
                            } else {
                                isBindWX = 0;
                                mWXNameTV.setText("绑定微信");
                                mBindWXTV.setText("立即绑定");
                                if (bean == null) {
                                    isAuthentication = 0;
                                    mUserInfoTV.setText("实名认证");
                                    mInformationOrAlterTV.setText("立即认证");
                                    mReviewLL.setVisibility(View.GONE);
                                    mInformationOrAlterTV.setVisibility(View.VISIBLE);
                                } else {
                                    if (bean.getIdStatus() == 11) {//审核成功
                                        isAuthentication = 1;
                                        idName = bean.getIdName();
                                        idCard = bean.getIdCard();
                                        mReviewLL.setVisibility(View.GONE);
                                        mInformationOrAlterTV.setVisibility(View.VISIBLE);
                                        mInformationOrAlterTV.setText("修改");
                                        mUserInfoTV.setText(bean.getIdName() + "  " + bean.getIdCard());
                                    } else if (bean.getIdStatus() == 1) {//正在审核中
                                        isAuthentication = 2;
                                        mReviewLL.setVisibility(View.VISIBLE);
                                        mInformationOrAlterTV.setVisibility(View.GONE);
                                        mUserInfoTV.setText(bean.getIdName() + "  " + bean.getIdCard());
                                    } else {
                                        isAuthentication = 0;
                                        mUserInfoTV.setText("实名认证");
                                        mInformationOrAlterTV.setText("立即认证");
                                        mReviewLL.setVisibility(View.GONE);
                                        mInformationOrAlterTV.setVisibility(View.VISIBLE);
                                    }
                                }
                            }
                        } else {
                            isBindWX = 0;
                            isAuthentication = 0;
                            mWXNameTV.setText("绑定微信");
                            mBindWXTV.setText("立即绑定");
                            mUserInfoTV.setText("实名认证");
                            mInformationOrAlterTV.setText("立即认证");
                            mReviewLL.setVisibility(View.GONE);
                            mInformationOrAlterTV.setVisibility(View.VISIBLE);
                            showToast(result3.getMessage());
                        }
                    }
                });
                return true;
        }
        return super.handleMessage(msg);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (RESULT_OK != resultCode) {
            return;
        }
        if (requestCode == 101) {
            int success = data.getIntExtra("success", 0);
            if (success == 0) {//操作成功
                String idName1 = data.getStringExtra("idName");
                String idCard1 = data.getStringExtra("idCard");
                //未认证，提交审核
                if (isAuthentication == 0) {
                    isAuthentication = 2;
                    mReviewLL.setVisibility(View.VISIBLE);
                    mInformationOrAlterTV.setVisibility(View.GONE);
                    mUserInfoTV.setText(idName1 + "  " + idCard1);
                } else {//修改认证
                    isAuthentication = 2;
                    mReviewLL.setVisibility(View.VISIBLE);
                    mInformationOrAlterTV.setVisibility(View.GONE);
                    mUserInfoTV.setText(idName1 + "  " + idCard1);
                }
            } else {
                //未认证，提交审核
                if (isAuthentication == 0) {
                    isAuthentication = 0;
                    mUserInfoTV.setText("实名认证");
                    mInformationOrAlterTV.setText("立即认证");
                    mReviewLL.setVisibility(View.GONE);
                    mInformationOrAlterTV.setVisibility(View.VISIBLE);
                } else {//修改

                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
